﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using KeanuMvc.Reference;
using HISModels.Entities;
using System.Net.Http;
using Microsoft.ApplicationServer.Http.Dispatcher;
using HISModels.ViewModel;

namespace HISRestServices.Services {

    [ServiceContract()]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public partial class Sys : BaseServices, IDisposable {

        //[ServiceWeb.Libs.BasicHttpAuthorization(UserRole = "admin")]
        #region Field
        private HttpStatusCode statusCode = new HttpStatusCode();
        private string detailMessage = string.Empty;
        #endregion

        #region Navigations

        [WebGet(UriTemplate = "navigations/{id}")]
        public HttpResponseMessage<SysNavigation> GetNavigationByID(int id) {
            HttpResponseMessage<SysNavigation> returnValue = null;
            SysNavigation sysnavigation = null;

            try {
                sysnavigation = AppContext.SysNavigations.Where(p => p.Id == id).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigation>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigation>(sysnavigation);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }


        [WebGet(UriTemplate = "navigations/group/{groupid}")]
        public HttpResponseMessage<List<SysNavigation>> GetNavigationByGroupID(int groupid) {
            HttpResponseMessage<List<SysNavigation>> returnValue = null;
            List<SysNavigation> listnavigation = null;
            try {
                listnavigation = AppContext.SysNavigations.Where(p => p.NavigationGroupId == groupid).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<SysNavigation>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysNavigation>>(listnavigation);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }


        [WebInvoke(Method = "POST", UriTemplate = "navigations/paging/")]
        public HttpResponseMessage<DataTablesNet> GetNavigationAllPost(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;

            DataTablesNet paging = new DataTablesNet();
            try {
                paging.sEcho = pagingSearch.sEcho;

                var a = from b in AppContext.SysNavigations select b;
                paging.iTotalRecords = a.Count();
                a = a.Where(p => p.DescValue.Contains(pagingSearch.sSearch));
                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "navigations/")]
        public HttpResponseMessage<SysNavigation> UpdateNavigation(SysNavigation paramObject) {
            HttpResponseMessage<SysNavigation> returnValue = null;

            try {
                if (AppContext.SysNavigations.Where(a => a.Id != paramObject.Id && a.DescValue == paramObject.DescValue && a.NavigationGroupId == paramObject.NavigationGroupId).Count() > 0) {
                    detailMessage = "Title name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                }
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigation>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigation>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "navigations/")]
        public HttpResponseMessage<SysNavigation> InsertNavigation(SysNavigation paramObject) {

            HttpResponseMessage<SysNavigation> returnValue = null;
            try {
                if (AppContext.SysNavigations.Where(a => a.DescValue == paramObject.DescValue && a.NavigationGroupId == paramObject.NavigationGroupId).Count() > 0) {
                    detailMessage = "Title name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                }
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigation>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigation>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "navigations/")]
        public HttpResponseMessage<SysNavigation> DeleteNavigationByID(int id) {
            HttpResponseMessage<SysNavigation> returnValue = null;
            SysNavigation objectDelete = null;
            try {
                List<SysNavigation> listNav = AppContext.SysNavigations.Where(a => a.ParentId == id).ToList();
                foreach (SysNavigation item in listNav) {
                    item.ParentId = 0;
                }
                objectDelete = AppContext.SysNavigations.Where(a => a.Id == id).First();
                AppContext.SysNavigations.Remove(objectDelete);
                AppContext.SaveChanges(UserId);

                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigation>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigation>(objectDelete);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "navigations/handleupdateparentid/{parentid}")]
        public HttpResponseMessage<List<SysNavigation>> HandleUpdateParentId(int parentid) {
            HttpResponseMessage<List<SysNavigation>> returnValue = null;
            List<SysNavigation> listNav = null;
            try {
                listNav = AppContext.SysNavigations.Where(a => a.ParentId == parentid).ToList();
                foreach (SysNavigation item in listNav) {
                    item.ParentId = 0;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
                //returnValue = "Error Occured on HandleDeleteParentId";
            } finally {
                returnValue = new HttpResponseMessage<List<SysNavigation>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysNavigation>>(listNav);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Navigations Group
        [WebGet(UriTemplate = "navigationgroups/{id}")]
        public HttpResponseMessage<SysNavigationGroup> GetNavigationGroupByID(int id) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            SysNavigationGroup sysNavGroup = null;
            try {
                sysNavGroup = AppContext.SysNavigationGroups.Include("SysRole").Where(a => a.Id == id).First();
                sysNavGroup.SysRole.RefHu = AppContext.RefHus.Where(a => a.Id == sysNavGroup.SysRole.HospitalUnitId).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(sysNavGroup);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "navigationgroupsrole/{rolename}")]
        public HttpResponseMessage<SysNavigationGroup> GetNavigationRole(string rolename) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            SysNavigationGroup sysNavGroup = null;
            try {
                sysNavGroup = (from b in AppContext.SysNavigationGroups
                               join c in AppContext.SysRoles on b.RoleId equals c.RoleId
                               where c.DescValue == rolename
                               select b).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(sysNavGroup);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebGet(UriTemplate = "navigationgroupsrolebyroleid/{roleid}")]
        public HttpResponseMessage<SysNavigationGroup> GetNavigationRoleByID(int roleid) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            SysNavigationGroup sysNavGroup = null;
            try {
                sysNavGroup = (from b in AppContext.SysNavigationGroups
                               join c in AppContext.SysRoles on b.RoleId equals c.RoleId
                               where c.RoleId == roleid
                               select b).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(sysNavGroup);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "navigationgroups/paging/")]
        public HttpResponseMessage<DataTablesNet> GetNavigationByGroupAllPost(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] param = null;

            string groupname = string.Empty;
            string hospitalid = string.Empty;
            string rolename = string.Empty;

            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                param = pagingSearch.sSearch.Split(';');

                groupname = param[0].Split('=')[1].NullSafeToString();
                rolename = param[1].Split('=')[1].NullSafeToString();
                hospitalid = param[2].Split('=')[1].NullSafeToString();

                int huid = Convert.ToInt32(hospitalid);

                var a = from b in AppContext.SysNavigationGroups
                        join c in AppContext.SysRoles on b.RoleId equals c.RoleId
                        join d in AppContext.RefHus on c.HospitalUnitId equals d.Id
                        select new {
                            b.Id,
                            b.DescValue,
                            RoleName = c.DescValue,
                            c.HospitalUnitId,
                            HospitalName = d.NameValue
                        };
                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.RoleName.Contains(rolename) || p.DescValue.Contains(groupname));

                if (huid > -1) {
                    a = a.Where(p => p.HospitalUnitId == huid);
                }

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }

            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;

        }

        [WebInvoke(Method = "PUT", UriTemplate = "navigationgroups/")]
        public HttpResponseMessage<SysNavigationGroup> UpdateNavigationGroup(SysNavigationGroup paramObject) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            string MrnNumb = string.Empty;

            try {

                if (AppContext.SysNavigationGroups.Where(a => a.Id != paramObject.Id && a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Group name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;


        }

        [WebInvoke(Method = "POST", UriTemplate = "navigationgroups/")]
        public HttpResponseMessage<SysNavigationGroup> InsertNavigationGroup(SysNavigationGroup paramObject) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            string MrnNumb = string.Empty;

            try {
                if (AppContext.SysNavigationGroups.Where(a => a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Group name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "navigationgroups/")]
        public HttpResponseMessage<SysNavigationGroup> DeleteNavigationGroupByID(int id) {
            HttpResponseMessage<SysNavigationGroup> returnValue = null;
            SysNavigationGroup objectDelete = null;
            try {
                objectDelete = AppContext.SysNavigationGroups.Where(a => a.Id == id).First();
                AppContext.SysNavigationGroups.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysNavigationGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysNavigationGroup>(objectDelete);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }
        #endregion

        #region Membership
        [WebGet(UriTemplate = "membership/{id}")]
        public HttpResponseMessage<AnonymousHeaderDetail> GetMembershipByID(int id)
        {
            HttpResponseMessage<AnonymousHeaderDetail> returnValue = null;
            AnonymousHeaderDetail sysmembership = null;
    
            try {

                sysmembership = new AnonymousHeaderDetail();

                

                var a = from b in AppContext.SysMemberships
                        join c in AppContext.MemberEmployees on b.Id equals c.MembershipId into d
                        from c in d.DefaultIfEmpty()
                        join e in AppContext.Employees on c.EmployeeId equals e.Id into f
                        from e in f.DefaultIfEmpty()
                        where b.Id == id
                        select new {
                            membershipid = b.Id,
                            b.RoleId,
                            b.IsApproved,
                            b.UserId,
                            name = e.FirstName +" "+ e.LastName,
                            employeeid = c.EmployeeId
                        };


                sysmembership.Detail = a;
               
                //sysmembership = AppContext.SysMemberships.Where(a => a.Id == id).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<AnonymousHeaderDetail>(statusCode);
                returnValue.Content = new ObjectContent<AnonymousHeaderDetail>(sysmembership);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "membership/user/{userid}")]
        public HttpResponseMessage<SysMembership> GetMembershipByUserID(string userid) {
            HttpResponseMessage<SysMembership> returnValue = null;
            SysMembership sysmembership = null;
            try {
                sysmembership = AppContext.SysMemberships.Include("SysRole").Where(a => a.UserId == userid).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysMembership>(statusCode);
                returnValue.Content = new ObjectContent<SysMembership>(sysmembership);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "membership/paging/")]
        public HttpResponseMessage<DataTablesNet> GetMembershipAllPost(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = pagingSearch.sEcho;
            string[] arrParam = null;
            string memberName = string.Empty;
            int huId = 0;
            string roleName = string.Empty;

            try {
                arrParam = pagingSearch.sSearch.Split(';');
                memberName = arrParam[0].Split('=')[1].NullSafeToString();
                huId = Convert.ToInt32(arrParam[1].Split('=')[1].ToString());
                roleName = arrParam[2].Split('=')[1].NullSafeToString();

                var a = from b in AppContext.SysMemberships
                        join c in AppContext.SysRoles on b.RoleId equals c.RoleId
                        join d in AppContext.RefHus on c.HospitalUnitId equals d.Id
                        where c.RoleId > 0
                        select new {
                            b.Id,
                            b.UserId,
                            b.RoleId,
                            ApproveStatus = b.IsApproved == 3 ? "Yes" : "No",
                            c.DescValue,
                            c.HospitalUnitId,
                            HospLocation = d.NameValue
                        };
                paging.iTotalRecords = a.Count();
                a = a.Where(p => p.DescValue.Contains(roleName) && p.UserId.Contains(memberName));

                if (huId > -1) {
                    a = a.Where(p => p.HospitalUnitId == huId);
                }
                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "membership/")]
        public HttpResponseMessage<SysMembership> UpdateMembership(SysMembership paramObject) {
            HttpResponseMessage<SysMembership> returnValue = null;
            string MrnNumb = string.Empty;

            try {

                if (AppContext.SysMemberships.Where(a => a.Id != paramObject.Id && a.UserId == paramObject.UserId).Count() > 0) {
                    detailMessage = "UserID already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;

            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysMembership>(statusCode);
                returnValue.Content = new ObjectContent<SysMembership>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;


        }

        [WebInvoke(Method = "POST", UriTemplate = "memberemployees/")]
        public HttpResponseMessage<MemberEmployee> InsertMemberEmployees(MemberEmployee paramObject)
        {
            HttpResponseMessage<MemberEmployee> returnValue = null;
            string MrnNumb = string.Empty;

            try
            {

                if (AppContext.MemberEmployees.Where(a => a.Id != paramObject.Id && a.EmployeeId == paramObject.EmployeeId && a.MembershipId == paramObject.MembershipId).Count() > 0)
                {
                    detailMessage = "Data already exist!";
                    paramObject = null;
                }
                else
                {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;

            }
            catch (Exception ex)
            {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            finally
            {
                returnValue = new HttpResponseMessage<MemberEmployee>(statusCode);
                returnValue.Content = new ObjectContent<MemberEmployee>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "membership/")]
        public HttpResponseMessage<SysMembership> InsertMembership(SysMembership paramObject)
        {
            HttpResponseMessage<SysMembership> returnValue = null;
            string MrnNumb = string.Empty;
            try
            {
                if (AppContext.SysMemberships.Where(a => a.UserId == paramObject.UserId).Count() > 0)
                {
                    detailMessage = "UserID already exist!";
                    paramObject = null;
                }
                else
                {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;

            }
            catch (Exception ex)
            {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            finally
            {
                returnValue = new HttpResponseMessage<SysMembership>(statusCode);
                returnValue.Content = new ObjectContent<SysMembership>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "membership/")]
        public string DeleteMembershipByID(int id) {
            string returnValue = string.Empty;
            try {
                SysMembership objectDelete = AppContext.SysMemberships.Where(a => a.Id == id).First();
                AppContext.SysMemberships.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
            } catch {
                returnValue = "Error deleting row!";
            }

            return returnValue;
        }

        #endregion

        #region Role
        [WebGet(UriTemplate = "roles/")]
        public HttpResponseMessage<List<SysRole>> GetRoles() {
            HttpResponseMessage<List<SysRole>> returnValue = null;
            List<SysRole> listSysRole = null;
            try {
                listSysRole = (from a in AppContext.SysRoles where a.RoleId > 0 select a).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<SysRole>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysRole>>(listSysRole);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "roles/{id}")]
        public HttpResponseMessage<SysRole> GetRoleByID(int id) {
            HttpResponseMessage<SysRole> returnValue = new HttpResponseMessage<SysRole>(AppContext.SysRoles.Where(a => a.RoleId == id && a.RoleId > 0).FirstOrDefault());
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "roles/paging/")]
        public HttpResponseMessage<DataTablesNet> GetRoleAllPost(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = null;
            HttpResponseMessage<DataTablesNet> returnValue = null;
            string[] param = null;

            string hospitalid = string.Empty;
            string rolename = string.Empty;

            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;
                param = pagingSearch.sSearch.Split(';');


                rolename = param[0].Split('=')[1].NullSafeToString();
                hospitalid = param[1].Split('=')[1].NullSafeToString();

                int huid = Convert.ToInt32(hospitalid);
                //var a = from b in AppContext.SysRoles where b.RoleId > 0 select b;
                var a = from b in AppContext.SysRoles
                        join c in AppContext.RefHus on b.HospitalUnitId equals c.Id
                        where b.RoleId > 0
                        select new {
                            b.HospitalUnitId,
                            b.RoleId,
                            RoleName = b.DescValue,
                            Location = c.NameValue
                        };

                paging.iTotalRecords = a.Count();

                a = a.Where(p => p.RoleName.Contains(rolename));

                if (huid > -1) {
                    a = a.Where(p => p.HospitalUnitId == huid);
                }

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.RoleName);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
            returnValue.Content = new ObjectContent<DataTablesNet>(paging);

            if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "roles/")]
        public HttpResponseMessage<SysRole> UpdateRole(SysRole paramObject) {
            HttpResponseMessage<SysRole> returnValue = null;
            string MrnNumb = string.Empty;

            try {

                if (AppContext.SysRoles.Where(a => a.RoleId != paramObject.RoleId && a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Role already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysRole>(statusCode);
                returnValue.Content = new ObjectContent<SysRole>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;


        }

        [WebInvoke(Method = "POST", UriTemplate = "roles/")]
        public HttpResponseMessage<SysRole> InsertRole(SysRole paramObject) {
            HttpResponseMessage<SysRole> returnValue = null;
            string MrnNumb = string.Empty;
            try {
                if (AppContext.SysRoles.Where(a => a.DescValue == paramObject.DescValue && a.RoleId > 0).Count() > 0) {
                    detailMessage = "Role Name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                }
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysRole>(statusCode);
                returnValue.Content = new ObjectContent<SysRole>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "roles/")]
        public string DeleteRoleByID(int id) {
            string returnValue = string.Empty;
            try {
                SysRole objectDelete = AppContext.SysRoles.Where(a => a.RoleId == id && a.RoleId > 0).First();
                AppContext.SysRoles.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
            } catch {
                returnValue = "Error deleting row!";
            }

            return returnValue;
        }

        #endregion

        #region Role Action
        [WebGet(UriTemplate = "roleactions/{id}")]
        public HttpResponseMessage<SysRoleAction> GetRoleActionByID(int id) {
            HttpResponseMessage<SysRoleAction> returnValue = new HttpResponseMessage<SysRoleAction>(AppContext.SysRoleActions.Where(a => a.ActionId == id).FirstOrDefault());
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "roleactions/paging/")]
        public HttpResponseMessage<DataTablesNet> GetRoleActionAllPost(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = pagingSearch.sEcho;

            var a = from b in AppContext.SysRoleActions select b;
            paging.iTotalRecords = a.Count();
            paging.iTotalDisplayRecords = a.Count();

            a = a.OrderBy(b => b.ActionId);
            a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

            paging.aaData = a;

            HttpResponseMessage<DataTablesNet> returnValue = new HttpResponseMessage<DataTablesNet>(
                paging
            );
            return returnValue;
        }

        [WebInvoke(Method = "GET", UriTemplate = "roleactions/user/{userid}")]
        public HttpResponseMessage<Array> GetRoleActionByUserId(string userid) {
            var a = from b in AppContext.SysMemberships
                    join c in AppContext.SysRoleActions on b.RoleId equals c.RoleId
                    select new {
                        c.RoleId
                    };
            HttpResponseMessage<Array> returnValue = new HttpResponseMessage<Array>(
               a.ToArray()
            );
            if (a.Count() == 0) {
                HttpResponseMessage noContentResponse = new HttpResponseMessage();
                noContentResponse.StatusCode = HttpStatusCode.NoContent;
                noContentResponse.Content = new StringContent("Record not found.");
                throw new HttpResponseException(noContentResponse);
            }
            return returnValue;
        }

        [WebInvoke(Method = "GET", UriTemplate = "roleactions/userinroleaction/{userid}/{roleid}")]
        public HttpResponseMessage<int> IsUserInRoleAction(string userid, int roleid) {
            var a = from b in AppContext.SysMemberships
                    join c in AppContext.SysRoleActions on b.RoleId equals c.RoleId
                    where b.UserId == userid && c.RoleId == roleid
                    select b;
            HttpResponseMessage<int> returnValue = new HttpResponseMessage<int>(
               a.Count()
            );
            return returnValue;
        }

        [WebInvoke(Method = "GET", UriTemplate = "roleactions/role/{roleid}")]
        public HttpResponseMessage<IQueryable> GetRoleActionByRoleId(int roleid) {
            HttpResponseMessage<IQueryable> returnValue = null;
            IQueryable data = null;
            try {
                var a = from b in AppContext.SysRoleActions
                        join c in AppContext.SysActions on b.ActionId equals c.Id
                        select new {
                            roleid = b.RoleId,
                            actionname = c.DescValue
                        };
                a = a.Where(p => p.roleid == roleid);

                if (a.Count() == 0) {
                    HttpResponseMessage noContentResponse = new HttpResponseMessage();
                    noContentResponse.StatusCode = HttpStatusCode.NoContent;
                    noContentResponse.Content = new StringContent("Record not found.");
                    throw new HttpResponseException(noContentResponse);
                }
                data = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<IQueryable>(statusCode);
            returnValue.Content = new ObjectContent<IQueryable>(data);
            if (data == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "roleactions/")]
        public string UpdateRoleAction(SysRoleAction paramObject) {
            string returnValue = string.Empty;
            if (AppContext.SysRoleActions.Where(a => a.RoleId != paramObject.RoleId && a.ActionId == paramObject.ActionId).Count() > 0) {
                returnValue = "Role already exist!";
                paramObject = null;
            } else {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "roleactions/")]
        public string InsertRoleAction(SysRoleAction paramObject) {
            string returnValue = string.Empty;
            if (AppContext.SysRoleActions.Where(a => a.ActionId == paramObject.ActionId).Count() > 0) {
                returnValue = "UserID already exist!";
                paramObject = null;
            } else {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                AppContext.SaveChanges(UserId);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "roleactions/")]
        public string DeleteRoleActionByID(int id) {
            string returnValue = string.Empty;
            try {
                SysRoleAction objectDelete = AppContext.SysRoleActions.Where(a => a.RoleId == id).First();
                AppContext.SysRoleActions.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
            } catch {
                returnValue = "Error deleting row!";
            }

            return returnValue;
        }
        #endregion

        #region Action
        [WebGet(UriTemplate = "actions/{id}")]
        public HttpResponseMessage<SysAction> GetActionByGroupId(int id) {
            HttpResponseMessage<SysAction> returnValue = null;
            SysAction sysAction = null;
            try {
                sysAction = new SysAction();
                sysAction = (from a in AppContext.SysActions
                             join b in AppContext.SysActionGroups on a.ActionGroupId equals b.Id
                             where a.Id == id
                             select a).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysAction>(statusCode);
                returnValue.Content = new ObjectContent<SysAction>(sysAction);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebGet(UriTemplate = "actions/list")]
        public HttpResponseMessage<List<SysAction>> GetListAction() {
            HttpResponseMessage<List<SysAction>> returnValue = null;
            List<SysAction> listSysAction = null;
            try {

                listSysAction = AppContext.SysActions.ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<SysAction>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysAction>>(listSysAction);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "actions/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAction(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] param = null;


            //int HuId = HospitalId;
            string key = string.Empty;
            int id = 0;
            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                param = pagingSearch.sSearch.Split(';');
                key = param[0].Split('=')[1].NullSafeToString();
                id = Convert.ToInt32(param[1].Split('=')[1]);
                var a = from b in AppContext.SysActions
                        join c in AppContext.SysActionGroups on b.ActionGroupId equals c.Id
                        where b.ActionGroupId == id
                        select new {
                            b.ActionGroupId,
                            b.DescValue,
                            b.Id
                        };
                paging.iTotalRecords = a.Count();
                a = a.Where(p => p.DescValue.Contains(key));

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "actions/")]
        public HttpResponseMessage<SysAction> UpdateAction(SysAction paramObject) {
            HttpResponseMessage<SysAction> returnValue = null;
            try {
                if (AppContext.SysActions.Where(a => a.Id != paramObject.Id && a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Action name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysAction>(statusCode);
                returnValue.Content = new ObjectContent<SysAction>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "actions/")]
        public HttpResponseMessage<SysAction> InsertAction(SysAction paramObject) {
            HttpResponseMessage<SysAction> returnValue = null;
            try {
                if (AppContext.SysActions.Where(a => a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Action name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysAction>(statusCode);
                returnValue.Content = new ObjectContent<SysAction>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "actions/")]
        public HttpResponseMessage<SysAction> DeleteActionByID(int id) {
            HttpResponseMessage<SysAction> returnValue = null;
            SysAction objectDelete = null;
            try {

                objectDelete = AppContext.SysActions.Where(a => a.Id == id).First();
                AppContext.SysActions.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysAction>(statusCode);
                returnValue.Content = new ObjectContent<SysAction>(objectDelete);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;
        }

        #endregion

        #region Audit Log

        [WebInvoke(Method = "POST", UriTemplate = "auditlog/paging/")]
        public HttpResponseMessage<DataTablesNet> GetAuditLog(PostDataTablesNet pagingSearch) {
            HttpResponseMessage<DataTablesNet> returnValue = null;
            DataTablesNet paging = null;
            string[] data = null;

            string key = string.Empty;

            try {
                paging = new DataTablesNet();
                paging.sEcho = pagingSearch.sEcho;

                data = pagingSearch.sSearch.Split(';');
                key = data[0].Split('=')[1].NullSafeToString();

                var a = from b in AppContext.SysLogs
                        select new {
                            b.Id,
                            b.UserID,
                            b.EventDateUTC,
                            EventType = b.EventType == "A" ? "Added" : b.EventType == "M" ? "Modified" : "Deleted",
                            b.RecordID,
                            b.ColumnName,
                            b.BeforeValue,
                            b.CurrentValue
                        };

                paging.iTotalRecords = a.Count();

                paging.iTotalDisplayRecords = a.Count();

                a = a.OrderBy(b => b.Id);
                a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

                paging.aaData = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<DataTablesNet>(statusCode);
                returnValue.Content = new ObjectContent<DataTablesNet>(paging);
                if (paging == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }


            return returnValue;
        }
        #endregion

        #region Actions Group
        [WebGet(UriTemplate = "actiongroups/{id}")]
        public HttpResponseMessage<SysActionGroup> GetActionGroupByID(int id) {
            HttpResponseMessage<SysActionGroup> returnValue = null;
            SysActionGroup sysActionGroup = null;
            try {
                sysActionGroup = AppContext.SysActionGroups.Where(d => d.Id == id).First();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysActionGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysActionGroup>(sysActionGroup);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebGet(UriTemplate = "actiongroups/")]
        public HttpResponseMessage<List<SysActionGroup>> GetListActionGroup() {
            HttpResponseMessage<List<SysActionGroup>> returnValue = null;
            List<SysActionGroup> listSysActionGroup = null;
            try {
                listSysActionGroup = AppContext.SysActionGroups.ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<SysActionGroup>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysActionGroup>>(listSysActionGroup);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }

        [WebInvoke(Method = "GET", UriTemplate = "actiongroups/{groupid}/{roleid}")]
        public HttpResponseMessage<AnonymousHeaderDetail> GetActionGroupByGroupId(int groupid, int roleid) {
            HttpResponseMessage<AnonymousHeaderDetail> returnValue = null;
            AnonymousHeaderDetail wrapper = new AnonymousHeaderDetail();
            try {

                var header = AppContext.SysRoles.Where(y => y.RoleId == roleid).First();
                wrapper.Header = header;

                var a = (from b in AppContext.SysActions.Where(t => t.ActionGroupId == groupid)
                         join c in AppContext.SysRoleActions.Where(t => t.RoleId == roleid)
                         on b.Id equals c.ActionId into temp1
                         from d in temp1.DefaultIfEmpty()
                         select new {
                             b.Id,
                             b.DescValue,
                             RoleID = d.RoleId == null ? 0 : 1
                         }
                        );
                wrapper.Detail = a;
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<AnonymousHeaderDetail>(statusCode);
                returnValue.Content = new ObjectContent<AnonymousHeaderDetail>(wrapper);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebGet(UriTemplate = "actiongroupsrole/{rolename}")]
        public HttpResponseMessage<SysActionGroup> GetActionRole(string rolename) {
            var a = from b in AppContext.SysActionGroups
                    join c in AppContext.SysRoles on b.Id equals c.RoleId
                    where c.DescValue == rolename
                    select b;
            HttpResponseMessage<SysActionGroup> returnValue = new HttpResponseMessage<SysActionGroup>(a.First());
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "actiongroups/role/")]
        public HttpResponseMessage<List<SysRoleAction>> UpdateListRoleAction(List<SysRoleAction> parameter) {
            HttpResponseMessage<List<SysRoleAction>> returnValue = null;
            List<SysRoleAction> data = null;
            if (parameter == null) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = "Value can not be null !";
                returnValue = new HttpResponseMessage<List<SysRoleAction>>(statusCode);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
                return returnValue;
            }
            if (parameter.Count == 0) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = "Value can not be empty !";
                returnValue = new HttpResponseMessage<List<SysRoleAction>>(statusCode);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
                return returnValue;
            }
            int aid = parameter[0].ActionId;
            int rid = parameter[0].RoleId;


            try {
                AppContext.Database.ExecuteSqlCommand(
                                @"DELETE FROM SysRoleActions WHERE SysRoleActions.ActionId IN 
                                (
                                    SELECT SysActions.Id FROM 
                                    SysActionGroups INNER JOIN SysActions ON  SysActionGroups.Id = SysActions.ActionGroupId 
                                    WHERE SysActionGroups.Id IN
                                        (
                                            SELECT SysActions.ActionGroupId FROM SysActions WHERE  SysActions.Id ={0}
                                        )               
                                 )
                                AND RoleId ={1} ", aid, rid
                            );

                AppContext.SaveChanges(UserId);



                for (int i = 0; i < parameter.Count; i++) {
                    AppContext.Entry(parameter[i]).State = System.Data.EntityState.Added;

                }

                AppContext.SaveChanges(UserId);
                detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                statusCode = HttpStatusCode.OK;
                data = parameter;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<List<SysRoleAction>>(statusCode);
                returnValue.Content = new ObjectContent<List<SysRoleAction>>(data);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }


        [WebInvoke(Method = "DELETE", UriTemplate = "actiongroups/role/")]
        public HttpResponseMessage<string> DeleteRoleActionByParameter(string parameter) {
            HttpResponseMessage<string> returnValue = null;
            string[] param = null;

            if (parameter == null) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = "Value can not be null !";
                returnValue = new HttpResponseMessage<string>(statusCode);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
                return returnValue;
            }

            param = parameter.Split(';');

            int agid = Convert.ToInt32(param[0].Split('=')[1]);
            int rid = Convert.ToInt32(param[1].Split('=')[1]);

            try {
                AppContext.Database.ExecuteSqlCommand(
                                @"DELETE FROM SysRoleActions WHERE SysRoleActions.ActionId IN 
                                (
                                    SELECT SysActions.Id FROM 
                                    SysActionGroups INNER JOIN SysActions ON  SysActionGroups.Id = SysActions.ActionGroupId 
                                    WHERE SysActionGroups.Id = {0}        
                                 )
                                AND RoleId ={1} ", agid, rid
                            );

                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
                detailMessage = HISModels.Enums.ResponseMessage.DeleteSuccess;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<string>(statusCode);
                returnValue.Content = new ObjectContent<string>(detailMessage);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }
            return returnValue;
        }


        [WebInvoke(Method = "POST", UriTemplate = "actiongroups/paging/")]
        public HttpResponseMessage<DataTablesNet> GetActionByGroupAllPost(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = pagingSearch.sEcho;

            var a = from b in AppContext.SysActionGroups
                    select new {
                        b.Id,
                        b.DescValue
                    };

            paging.iTotalRecords = a.Count();
            a = a.Where(p => p.DescValue.Contains(pagingSearch.sSearch));
            paging.iTotalDisplayRecords = a.Count();

            a = a.OrderBy(b => b.Id);
            a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

            paging.aaData = a;

            HttpResponseMessage<DataTablesNet> returnValue = new HttpResponseMessage<DataTablesNet>(
                paging
            );
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "actiongroups/")]
        public HttpResponseMessage<SysActionGroup> UpdateActionGroup(SysActionGroup paramObject) {

            HttpResponseMessage<SysActionGroup> returnValue = null;
            try {
                if (AppContext.SysActionGroups.Where(a => a.Id != paramObject.Id && a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Group name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.UpdateSuccess;
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysActionGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysActionGroup>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "actiongroups/")]
        public HttpResponseMessage<SysActionGroup> InsertActionGroup(SysActionGroup paramObject) {
            HttpResponseMessage<SysActionGroup> returnValue = null;

            try {
                if (AppContext.SysActionGroups.Where(a => a.DescValue == paramObject.DescValue).Count() > 0) {
                    detailMessage = "Group name already exist!";
                    paramObject = null;
                } else {
                    AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                    AppContext.SaveChanges(UserId);
                    detailMessage = HISModels.Enums.ResponseMessage.InsertSuccess;
                }

                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysActionGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysActionGroup>(paramObject);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "actiongroups/")]
        public HttpResponseMessage<SysActionGroup> DeleteActionGroupByID(int id) {
            HttpResponseMessage<SysActionGroup> returnValue = null;
            SysActionGroup objectDelete = null;
            try {
                objectDelete = AppContext.SysActionGroups.Where(a => a.Id == id).First();
                AppContext.SysActionGroups.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            } finally {
                returnValue = new HttpResponseMessage<SysActionGroup>(statusCode);
                returnValue.Content = new ObjectContent<SysActionGroup>(objectDelete);
                returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);
            }

            return returnValue;
        }
        #endregion

        #region Option
        [WebGet(UriTemplate = "options/{id}")]
        public HttpResponseMessage<SysOption> GetOptionByID(int id) {
            HttpResponseMessage<SysOption> returnValue = new HttpResponseMessage<SysOption>(AppContext.SysOptions.Where(a => a.Id == id).First());
            return returnValue;
        }


        [WebGet(UriTemplate = "options/group/{groupid}")]
        public HttpResponseMessage<List<SysOption>> GetOptionByGroupID(int groupid) {
            HttpResponseMessage<List<SysOption>> returnValue = null;
            List<SysOption> listsysoption = null;
            try {
                listsysoption = AppContext.SysOptions.Where(a => a.GroupId == groupid).ToList();
                statusCode = HttpStatusCode.OK;
            } catch (Exception ex) {
                statusCode = HttpStatusCode.InternalServerError;
                detailMessage = ex.Message;
            }
            returnValue = new HttpResponseMessage<List<SysOption>>(statusCode);
            returnValue.Content = new ObjectContent<List<SysOption>>(listsysoption);
            if (listsysoption == null) returnValue.Headers.Add(HISModels.Enums.ResponseMessage.DetailHeadesMessageKey, detailMessage);

            return returnValue;
        }


        [WebInvoke(Method = "POST", UriTemplate = "options/paging/")]
        public HttpResponseMessage<DataTablesNet> GetOptionAllPost(PostDataTablesNet pagingSearch) {

            DataTablesNet paging = new DataTablesNet();
            paging.sEcho = pagingSearch.sEcho;

            var a = from b in AppContext.SysOptions select b;
            paging.iTotalRecords = a.Count();
            a = a.Where(p => p.DescValue.Contains(pagingSearch.sSearch));
            paging.iTotalDisplayRecords = a.Count();

            a = a.OrderBy(b => b.Id);
            a = a.Skip(pagingSearch.iDisplayStart).Take(pagingSearch.iDisplayLength);

            paging.aaData = a;

            HttpResponseMessage<DataTablesNet> returnValue = new HttpResponseMessage<DataTablesNet>(
                paging
            );
            return returnValue;
        }

        [WebInvoke(Method = "PUT", UriTemplate = "options/")]
        public string UpdateOption(SysOption paramObject) {
            string returnValue = string.Empty;
            if (AppContext.SysOptions.Where(a => a.Id != paramObject.Id && a.DescValue == paramObject.DescValue).Count() > 0) {
                returnValue = "Role already exist!";
                paramObject = null;
            } else {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Modified;
                AppContext.SaveChanges(UserId);
            }
            return returnValue;
        }

        [WebInvoke(Method = "POST", UriTemplate = "options/")]
        public string InsertOption(SysOption paramObject) {
            string returnValue = string.Empty;
            if (AppContext.SysOptions.Where(a => a.DescValue == paramObject.DescValue).Count() > 0) {
                returnValue = "UserID already exist!";
                paramObject = null;
            } else {
                AppContext.Entry(paramObject).State = System.Data.EntityState.Added;
                AppContext.SaveChanges(UserId);
            }
            return returnValue;
        }

        [WebInvoke(Method = "DELETE", UriTemplate = "options/")]
        public string DeleteOptionByID(int id) {
            string returnValue = string.Empty;
            try {
                SysOption objectDelete = AppContext.SysOptions.Where(a => a.Id == id).First();
                AppContext.SysOptions.Remove(objectDelete);
                AppContext.SaveChanges(UserId);
            } catch {
                returnValue = "Error deleting row!";
            }

            return returnValue;
        }
        #endregion

        void IDisposable.Dispose() {
            try {
                base.Dispose();
                GC.SuppressFinalize(this);
            } catch { }
        }

    }
}